package Lab3;

public class LinkedListMine<E> {
	private LinkBox headOfList;
	private int itemCount;

	public LinkedListMine() {
		headOfList = null;
		itemCount = 0;
	}

	public void replace(int position, Object what) {
		LinkBox currItem = headOfList;
		LinkBox newItem = new LinkBox(what, null);
		
		if (position == 0) {
			headOfList = newItem;
			return;
		}
		
		if (position > itemCount - 1) {
			return;
		}
		
		for (int index = 0; index < position - 1; index++) {
			currItem = currItem.getNext();
		}
		
		currItem.setNext(newItem);
	}
	
	public void addAll(LinkedListMine<E> otherList) {
		LinkBox end = headOfList;
		
		while (end.getNext() != null) {
			end = end.getNext();
		}
		
		copyChain(end, otherList);
	}
	
	private void copyChain(LinkBox endOfList, LinkedListMine<E> listToCopy) {
		LinkBox otherEnd = listToCopy.headOfList;
		
		while (otherEnd != null) {
			endOfList.setNext(otherEnd.getNext());
			itemCount++;
			otherEnd = otherEnd.getNext();
		}
	}
	
	public void addAll(LinkedListMine<E> otherList, int mark) {
		LinkBox end = headOfList;
		LinkBox otherEnd = otherList.headOfList;
		
		while (end.getNext() != null) {
			end = end.getNext();
		}
		
		while (otherEnd != null) {
			end.setNext(otherEnd.getNext());
			itemCount++;
			otherEnd = otherEnd.getNext();
		}
	}
	
	public void add(Object theObject) {
		LinkBox newBox = new LinkBox(theObject, null);

		if (headOfList == null) {
			headOfList = newBox;
			itemCount++;
			return;
		}
		
		LinkBox end = headOfList;
		while (end.getNext() != null) {
			end = end.getNext();
		}

		end.setNext(newBox);

		itemCount++;
	}

	public Object getPosition(int position) {
		if (position > itemCount - 1) {
			return null;
		}

		LinkBox currentLink = headOfList;

		for (int index = 0; index < position; index++) {
			currentLink = currentLink.getNext();
		}

		return currentLink.getItem();
	}

	public int size() {
		return itemCount;
	}

	public void remove(int whichPosition) {
		if (whichPosition == 0) {
			headOfList = headOfList.getNext();
			return;
		}
		
		// Advance to the element just before the one we want to delete

		LinkBox theOneBefore = headOfList;

		for (int index = 0; index < whichPosition - 1; index++) {
			theOneBefore = theOneBefore.getNext();
		}

		LinkBox theOneToRemove = theOneBefore.getNext();
		LinkBox theOneAfter = theOneToRemove.getNext();
		theOneBefore.setNext(theOneAfter);

		itemCount--;
	}

	@Override
	public String toString() {
		String contents = "";

		if (headOfList == null) {
			return "null";
		}

		LinkBox currentLink = headOfList;

		for (int index = 0; index < itemCount; index++) {
			contents = contents + "[ " + currentLink.toString() + "] ";
			currentLink = currentLink.getNext();
		}

		return contents;
	}
}